<template>
  <div class="items">
    <el-row class="taskbar">
      <el-col :span="6">
        <div class="sort"></div>
      </el-col>
      <el-col :span="6"> </el-col>
      <el-col :span="6"><div class="sort"></div></el-col>
      <el-col :span="6"><div class="sort"></div></el-col>
      <el-rol :span="6">
        <div class="search">
          <el-input
            v-model="searchContent"
            placeholder="请输入要查找的商品"
            class="input-with-select"
            clearable
            @clear="serchback"
          >
            <template #append>
              <el-button @click="searchitem()">搜索</el-button>
            </template>
          </el-input>
        </div>
      </el-rol>
    </el-row>
    <div class="cardContainer">
      <el-card
        v-for="item in items"
        :key="item.id"
        :body-style="{ padding: '0' }"
      >
        <img
          :src="item.photos[0] ? baseUrl + item.photos[0].path : baseImg"
          alt="图片加载失败"
          @click="toItemid(item.id)"
        />
        <div class="info">
          <img
            v-if="false"
            src="../../assets/img/goods/collect_no.png"
            alt=""
            class="collect"
            @click="collect(item.id)"
          />
          <img
            v-if="!false"
            src="../../assets/img/goods/collect_yes.png"
            alt=""
            class="collect"
            @click="collect(item.id)"
          />
          <span>{{ iscollect }}</span>
          <h4>{{ item.name }}</h4>
          <span class="addTime">发布于{{ item.createdAt.slice(0, 10) }}</span>
          <span class="browsing">{{ 0 }}人浏览</span>
          <span class="describe">{{ item.description }}</span>
          <span class="price">
            <span class="newPrice">¥{{ item.price }}</span>
            <del class="oldPrice" v-if="item.originalPrice" style="color: grey">
              ¥{{ item.originalPrice }}
            </del>
          </span>
        </div>
      </el-card>
    </div>
    <pre>{{ errors }}</pre>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useErrors } from '../../composable/useErrors'
import {
  getItems,
  Item,
  changeFavorites,
  checkFavorites,
  favorite,
  setHistory
} from '../../services/items'
import { ElMessage } from 'element-plus'

const baseUrl = ref('http://159.75.101.15:3000/')
const baseImg = ref(
  'https://iconfont.alicdn.com/s/7a51524d-a4ce-4018-a386-9a03e0a044ee_origin.svg'
)
const items = ref()
const searchContent = ref('')
const { errors, errorHandler } = useErrors()
const iscollect = ref()

const collectYes = () => {
  ElMessage({
    message: '已收藏',
    type: 'success',
  })
}
const collectNo = () => {
  ElMessage({
    message: '取消收藏',
    type: 'warning',
  })
}


// 获取所有商品
// TODO: 支持分页，搜索和筛选
onMounted(async () => {
  try {
    items.value = (await getItems()).data
    items.value = items.value.filter((element: { status: string }) => {
      return element.status !== 'REQUEST' && element.status !== 'DRAFT'
    })
  } catch (err) {
    errorHandler(err)
  }
})

const router = useRouter()
const toItemid = async (id: string) => {
  let history = {
    count: 0
  }
  history = (await setHistory(id)).data
  console.log(history)

  router.push(`/itemDetails/${id}`)
}

function searchitem() {
  const result: {}[] = []
  items.value.forEach((Object: Item) => {
    if (Object.name.search(searchContent.value) !== -1) {
      result.push(Object)
    }
  })
  console.log(result)
  items.value = result
}

async function serchback() {
  items.value = (await getItems()).data
}

async function collect(id: string) {
  let isFavorite: favorite = {
    favorite: false
  }
  // console.log((await checkFavorites(id)).data)
  isFavorite = (await checkFavorites(id)).data
  isFavorite.favorite = !isFavorite.favorite

  await changeFavorites(id, isFavorite)
  if(isFavorite.favorite){
    collectYes()
  }else{
    collectNo()
  }
}
</script>

<style lang="less" scoped>
.items {
  margin-top: 30px;
}
.taskbar {
  margin: 20px 0;
  .sort {
    display: inline-block;
  }
  .search {
    display: inline-block;
    width: 500px;
  }
  overflow: hidden;
}
.cardContainer {
  column-count: 5;
  column-gap: 0px;
  column-width: 225px;
}
.el-card {
  display: inline-flex;
  margin-left: 10px;
  margin-bottom: 20px;
  width: 220px;
  height: auto;
  border-radius: 10px;
  cursor: pointer;
  img {
    width: 220px;
    transition: all 0.5s;
  }
  img:hover {
    transform: scale(1.5, 1.5);
  }
  .info {
    margin: 0 20px;
    margin-bottom: 10px;
    .addTime,
    .browsing {
      font-size: 12px;
      line-height: 20px;
      color: #93999f;
    }
    .collect {
      position: absolute;
      margin-left: 150px;
      width: 25px;
    }
    .addTime {
      margin-right: 30px;
    }
    .describe {
      display: block;
      width: 180px;
      height: auto;
      margin-top: 20px;
      font-size: 13px;
      line-height: 20px;
      color: chocolate;
      word-break: normal;
      white-space: pre-wrap;
      word-wrap: break-word;
      overflow: hidden;
    }
    .price {
      display: inline-block;
      margin-top: 15px;
      .newPrice {
        font-size: 13px;
        color: red;
      }
      .oldPrice {
        margin-left: 3px;
        font-size: 10px;
        color: gray;
      }
    }
  }
}
.a1 {
  height: 500px;
  width: 200px;
  background-color: aqua;
}
.el-input__suffix {
  .el-input__suffix-inner {
    border-color: none;
    .el-icon-circle-close:before {
      content: '\e79d' !important;
      font-size: 18px;
    }
  }
}
</style>
